/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaAsignacionAnimal.java
 *
 * Created on Sep 1, 2009, 12:31:06 PM
 */

package ac.view;

import ac.entities.Animal;
import ac.entities.Especie;
import ac.entities.Tanque;
import ac.entities.TanqueAnimal;
import ac.entities.Variedad;
import ac.logic.LogicAnimal;
import ac.logic.LogicEspecie;
import ac.logic.LogicTanque;
import ac.logic.LogicTanqueAnimal;
import ac.logic.LogicVariedad;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author prometheus
 */
public class VentanaAsignacionAnimal extends javax.swing.JFrame {

    private ArrayList<Animal> animales = null;
    private Animal seleccionado = null;
    private Especie especie = null;
    private ArrayList<Tanque> tanques = null;

    /** Creates new form VentanaAsignacionAnimal */
    public VentanaAsignacionAnimal() {
        LookAndFeel laf = new LookAndFeel();
        initComponents();
        DefaultListModel modelo = null;
        LogicAnimal la = new LogicAnimal();
        this.animales = la.buscarTodosAnimales();
        modelo = this.setearModelo();
        this.listaAnimales.setModel(modelo);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        campoNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        campoPeso = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        campoLongitud = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        campoLlegada = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        campoVariedad = new javax.swing.JTextField();
        campoEspecie = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        checkTanques = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaAnimales = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del Animal"));

        jLabel1.setText("Nombre:");

        jLabel2.setText("Peso:");

        jLabel3.setText("Longitud:");

        jLabel4.setText("Fecha de Llegada:");

        jLabel5.setText("Variedad:");

        jLabel6.setText("Especie:");

        jLabel7.setText("Tanques Sugeridos:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(campoLongitud)
                            .addComponent(campoPeso)
                            .addComponent(campoNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(campoEspecie, javax.swing.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(checkTanques, 0, 366, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(campoLlegada))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel5)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(campoVariedad, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(campoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(campoLongitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(campoLlegada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(campoVariedad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(campoEspecie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(checkTanques, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Animales"));

        listaAnimales.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaAnimalesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listaAnimales);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton1.setText("Confirmar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void listaAnimalesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaAnimalesMouseClicked
        int seleccion = this.listaAnimales.getSelectedIndex();
        this.seleccionado = this.animales.get(seleccion);
        this.buscarEspecieyVariedad();
        SimpleDateFormat formato = new SimpleDateFormat("dd-MM-yyyy");
        String fecha = formato.format(this.seleccionado.getFechaLlegada());

        String peso = Integer.toString(seleccionado.getPeso());
        String longitud = Integer.toString(seleccionado.getLongitud());

        this.campoLongitud.setText(longitud);
        this.campoPeso.setText(peso);

        this.campoLlegada.setText(fecha);
        this.campoNombre.setText(this.seleccionado.getNombre());

        this.cargarTanquesSugeridos(this.especie);
    }//GEN-LAST:event_listaAnimalesMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        String mensaje = "No se ha posiso asignar el animal al tanque";
        LogicTanqueAnimal lta = new LogicTanqueAnimal();
        LogicTanque lt = new LogicTanque();
        Tanque t = lt.buscarTanqueActual(this.seleccionado.getId());
        int idTanqueAnimal = lta.ultimoIdTanqueAnimal() + 1;
        int idAnimal = this.seleccionado.getId();
        int selectedTankOnList = this.checkTanques.getSelectedIndex();
        Tanque selected = this.tanques.get(selectedTankOnList - 1);
        int idTanque = selected.getId();
        Date fechaInicio = new Date();

        if ((this.validarTiempoCuarentena()) || (t == null)) {
            TanqueAnimal tanAni = new TanqueAnimal (idTanqueAnimal, fechaInicio,
                  idAnimal, idTanque);
            mensaje = lta.nuevoTanqueAnimal(tanAni);
            JOptionPane.showMessageDialog(this, mensaje, "Info", JOptionPane.INFORMATION_MESSAGE);
        } else if ((!this.validarTiempoCuarentena()) && (selected.getCuarentena().equalsIgnoreCase("si"))) {
            TanqueAnimal tanAni = new TanqueAnimal (idTanqueAnimal, fechaInicio,
                  idAnimal, idTanque);
            mensaje = lta.nuevoTanqueAnimal(tanAni);
            JOptionPane.showMessageDialog(this, mensaje, "Info", JOptionPane.INFORMATION_MESSAGE);
        }

        else {
            JOptionPane.showMessageDialog(this, "Error, el animal no ha completado su período de cuarentena",
                    "ERROR FATAL", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaAsignacionAnimal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField campoEspecie;
    private javax.swing.JTextField campoLlegada;
    private javax.swing.JTextField campoLongitud;
    private javax.swing.JTextField campoNombre;
    private javax.swing.JTextField campoPeso;
    private javax.swing.JTextField campoVariedad;
    private javax.swing.JComboBox checkTanques;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listaAnimales;
    // End of variables declaration//GEN-END:variables

    private DefaultListModel setearModelo() {
        DefaultListModel result = new DefaultListModel();
        for (Animal animal : animales) {
            result.addElement(animal.getNombre());
        }
        return result;
    }

    private void buscarEspecieyVariedad() {
        LogicVariedad lv = new LogicVariedad();
        LogicEspecie le = new LogicEspecie();
        Especie e = null;
        Variedad v = null;
        v = lv.buscarVariedadId(this.seleccionado.getIdVariedad());
        e = le.buscarEspecieId(v.getIdEspecie());
        this.especie = e;

        this.campoEspecie.setText(e.getNombreLat());
        this.campoVariedad.setText(v.getNombre());
    }

    private void cargarTanquesSugeridos(Especie especie) {
        this.checkTanques.removeAllItems();
        LogicTanque lt = new LogicTanque();
        this.tanques = lt.buscarTanquesEspecie(especie.getIdEspecie());
        Tanque tanqueActual = lt.buscarTanqueActual(this.seleccionado.getId());
        this.checkTanques.addItem("Seleccione un Tanque");
        for (Tanque t : this.tanques) {
            String tank = t.getForma() + " " + t.getMaterial() + " " +
                    t.getCapacidad() + " Lts";
            if (t.getCuarentena().equalsIgnoreCase("si")) {
                tank += " " + "Q";
            }
            if ((tanqueActual == null) && (t.getCuarentena().equalsIgnoreCase("si"))) {
                    this.checkTanques.addItem(tank);
            } else if (tanqueActual != null) {
                    this.checkTanques.addItem(tank);
            }
        }
    }

    private boolean validarTiempoCuarentena() {
        boolean result = false;
        Date hoy = new Date();
        int diasCuarentena = this.especie.getCuarentena();
        Date finCuarentena = this.seleccionado.getFechaLlegada();
        finCuarentena.setDate(finCuarentena.getDate() + diasCuarentena);

        if (hoy.after(finCuarentena)) {
            result = true;
        }
        return result;
    }

}
